import extentContext  from '../context.js';
import { bindThis } from '../tools/utils.js';

export default bindThis(class Api {
  static classType = 'ApiEntity';
  __v_skip = true;
  _contextPath = null;
  get classType() {
    return Api.classType;
  }


  constructor(options={}) {
    let self = this;
    self.contextPath = options.contextPath;
    self.baseUrl = options.baseUrl;
    self.request = options.request;
    if (!self.request){
      self.request = extentContext().axiosInstance;
    }
    if (options.apis){
      for(let key in options.apis){
        self[key] = options.apis[key];
      }
    }

    return new Proxy(self, {
      get(tagter, prop) {
        if (prop.startsWith('_')) {
          return tagter[prop];
        }
        if (typeof tagter[prop] === 'function') {
          return function(){
            return tagter[prop].apply(tagter, arguments);
          };
        } else {
          return tagter[prop];
        }
      }
    });
  }

  set contextPath(value) {
    if (!value.startsWith('/')){
      value = '/' + value;
    }
    if (value.endsWith('/')){
      value = value.substr(0, value.length - 1);
    }
    this._contextPath = value;
  }
  get contextPath(){
    return this._contextPath;
  }

  url(uri){
    if (!uri.startsWith('/')){
      uri = '/'+uri;
    }
    return this._contextPath + uri;
  }

  // 查询一条
  one(data) {
    let self = this;
    return self.request({
      baseUrl: self.baseUrl,
      url: self.contextPath + '/one',
      method: 'POST',
      data
    });
  }

  page(data) {
    let self = this;
    return self.request({
      baseUrl: self.baseUrl,
      url: self.contextPath,
      method: 'POST',
      data
    });
  }

  list(data) {
    let self = this;
    return self.request({
      baseUrl: self.baseUrl,
      url: self.contextPath + '/entitys',
      method: 'POST',
      data
    });
  }

  save(data) {
    let self = this;
    return self.request({
      baseUrl: self.baseUrl,
      url: self.contextPath,
      method: 'PUT',
      data
    });
  }

  updateById(id, data) {
    let self = this;
    if (!id) return Promise.reject('id不能为空');
    return self.request({
      baseUrl: self.baseUrl,
      url: self.contextPath + '/' + id,
      method: 'PUT',
      data
    });
  }

  saveOrUpdate(data, id) {
    id = id || data.id;
    if (id) {
      return this.updateById(id, data);
    } else {
      return this.save(data);
    }
  }

  deleteById(id) {
    if (!id) return Promise.reject('id不能为空');
    let self = this;
    return self.request({
      baseUrl: self.baseUrl,
      url: self.contextPath + '/' + id,
      method: 'delete',
    });
  }
});